local matLight		= {}
matLight[1] = Material( "sprites/light_ignorez" )
matLight[2] = Material( "sprites/redglow2" )

local matBeam = Material( "particle/outBeam" )
local matRefractive = Material( "models/shadertest/predator" )

for k,v in pairs(matLight) do
		v:SetMaterialInt("$spriterendermode", 9)
		v:SetMaterialInt("$ignorez", 1)
		v:SetMaterialInt("$illumfactor", 7)
end


function EFFECT:Init(data) 
 	 
	self.StartPos	= data:GetOrigin() 
	self.EntityE	= StargateExtras:FindEntInsideSphere(self.StartPos, 10, "event_horizon")[1]	-- Remote Gate
	self.EntityB	= data:GetEntity()	-- Remote Beam
	self.StartPos	= StargateExtras:GetEntityCentre(self.EntityE)
	self.EndPos	= Vector()
	self.HitNormal	= Vector()
	self.AimVector 	= Vector()
	self.Time	= CurTime()
	self.Length 	= 0
	self.Emit	= ParticleEmitter(self.StartPos)

	self.Entity:SetRenderBounds(-1*Vector()*100000,Vector()*100000)

	self.Vis = {util.GetPixelVisibleHandle(), util.GetPixelVisibleHandle()}
end

function EFFECT:Think() 
	if not (self.EntityE and self.EntityB and ValidEntity(self.EntityE) and self.EntityB:IsValid()) then return end

	self.Time = CurTime()
	
	self.StartPos 	= StargateExtras:GetEntityCentre2(self.EntityE)
	self.AimVector	= self.EntityE:GetForward()
   	        	
	local filter = { self.EntityB, self.EntityE }
      	
	local tr = StargateExtras:ShieldTrace(self.StartPos, self.AimVector*1000000, filter, true)
	
	self.EndPos = tr.HitPos
	self.Draw = ((self.EndPos:Distance(self.StartPos) > 10) and (not ValidEntity(StargateExtras:FindEntInsideSphere(self.StartPos, 50, "stargate_iris")[1])))

	return true
end 

function EFFECT:Render()
	if (self.Draw) then
		local texcoor = self.Time*-7		
		render.SetMaterial(matRefractive)
		render.DrawBeam(self.StartPos, self.EndPos, 75, texcoor, texcoor+self.Length/256)
		render.SetMaterial(matBeam)
		render.DrawBeam(self.StartPos, self.EndPos, 90, texcoor, texcoor+self.Length/256)
		render.DrawBeam(self.StartPos, self.EndPos, 120, texcoor, texcoor+self.Length/256, Color(255,0,0,150))
	
		if util.PixelVisible(self.StartPos, 100, self.Vis[1]) > 0 then
			local pos = self.StartPos + self.AimVector*4
			render.SetMaterial(matLight[1])
			render.DrawQuadEasy(pos, self.AimVector, 400, 400)
			render.SetMaterial(matLight[2])
			render.DrawQuadEasy(pos, self.AimVector, 450, 450)
		end

		local pos = self.EndPos-self.AimVector*5
		if util.PixelVisible(pos, 100, self.Vis[2]) > 0 then
			render.SetMaterial(matLight[1])
			render.DrawSprite(pos, 400, 400)
			render.SetMaterial(matLight[2])
			render.DrawSprite(pos, 450, 450)
		end	
	end
end
